package handler

import (
	"context"
	"fmt"
	"google.golang.org/protobuf/types/known/emptypb"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"shop/cart-srv/global"
	"shop/cart-srv/model"
	"shop/cart-srv/proto"
)

type InventorService struct {
}

func (i *InventorService) SetInv(ctx context.Context, req *proto.GoodsInvInfo) (*emptypb.Empty, error) {
	var invertory model.Invertory

	invertory.Goods = req.GoodsId
	invertory.Stocks = req.Num
	invertory.Version = 100

	global.Db.Create(&invertory)
	return &emptypb.Empty{}, nil
}
func (i *InventorService) InvDetail(context.Context, *proto.GoodsInvInfo) (*proto.GoodsInvInfo, error) {

	return &proto.GoodsInvInfo{}, nil
}

func (i *InventorService) Sell(ctx context.Context, req *proto.SellInfo) (*emptypb.Empty, error) {
	var invertory model.Invertory
	tx := global.Db.Begin()

	tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("goods=?", 10).First(&invertory)
	if invertory.Stocks <= 0 {
		fmt.Println("库存不足")
		return &emptypb.Empty{}, nil
	}
	fmt.Println("当前库存", invertory.Stocks)

	global.Db.Model(&invertory).Where("goods=?", 10).Update("stocks", gorm.Expr("stocks - ?", 1))
	//tx.Commit()

	return &emptypb.Empty{}, nil
}
func (i *InventorService) Reback(context.Context, *proto.SellInfo) (*emptypb.Empty, error) {
	return &emptypb.Empty{}, nil
}
